package com.zp.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.RegexPool;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.zp.annotations.AuthCheck;
import com.zp.constants.UserConstant;
import com.zp.domain.common.DeleteRequest;
import com.zp.domain.common.Result;
import com.zp.domain.entity.User;
import com.zp.domain.request.user.*;
import com.zp.domain.vo.CaptchaVO;
import com.zp.domain.vo.LoginUserVO;
import com.zp.domain.vo.UserDetailVO;
import com.zp.domain.vo.UserVO;
import com.zp.enums.ErrorCode;
import com.zp.exception.BusinessException;
import com.zp.service.PictureService;
import com.zp.service.UserService;
import com.zp.utils.ThrowUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.zp.configuration.AliyunOssClient;
import java.io.InputStream;

@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
@Api(tags = "用户模块")
public class UserController {
    private final UserService userService;
    private final PictureService pictureService;
    private final OSS ossClient;
    private final AliyunOssClient aliyunOssClient;

    /**
     * 发送邮箱验证码
     *
     * @param userRegisterRequest 用户注册请求
     * @return 验证码 key
     */
    @PostMapping("/send/email/code")
    public Result<String> sendEmailCode(@RequestBody com.zp.domain.request.user.UserRegisterRequest userRegisterRequest) {
        ThrowUtils.throwIf(userRegisterRequest == null, ErrorCode.PARAMS_ERROR);
        String userEmail = userRegisterRequest.getUserEmail();
        if (StrUtil.isEmpty(userEmail)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱不能为空");
        }
        // 校验邮箱格式
        if (StrUtil.isEmpty(userEmail) || !ReUtil.isMatch(RegexPool.EMAIL, userEmail)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }
        return Result.success(userService.sendEmailCode(userEmail));
    }

    /**
     * 用户注册
     *
     * @param request 注册参数
     * @return 注册成功的用户 id
     */
    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    @ApiOperationSupport(order = 1)
    public Result<Long> userRegister(@RequestBody com.zp.domain.request.user.UserRegisterRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        String userEmail = request.getUserEmail();
        String codeKey = request.getCodeKey();
        String codeValue = request.getCodeValue();
        if (StrUtil.hasBlank(userEmail, codeKey, codeValue)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // 校验邮箱格式
        if (StrUtil.isEmpty(userEmail) || !ReUtil.isMatch(RegexPool.EMAIL, userEmail)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }
        long userId = userService.userRegister(userEmail, codeKey, codeValue);
        return Result.success(userId);
    }

    /**
     * 用户登录
     *
     * @param loginRequest userAccount, userPassword
     * @param request      记录用户登录信息到 session
     * @return 登录用户信息(脱敏)
     */
    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    @ApiOperationSupport(order = 2)
    public Result<LoginUserVO> userLogin(@RequestBody com.zp.domain.request.user.UserLoginRequest loginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(loginRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = loginRequest.getUserAccount();
        String userPassword = loginRequest.getUserPassword();
        String captchaKey = loginRequest.getCaptchaKey();
        String captchaCode = loginRequest.getCaptchaCode();
        if (StrUtil.hasBlank(userAccount, userPassword, captchaKey, captchaCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        if (userAccount.length() < 4 || userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号或密码输入错误");
        }
        LoginUserVO loginUserVO = userService.userLogin(userAccount, userPassword, captchaKey, captchaCode, request);
        return Result.success(loginUserVO);
    }

    /**
     * 获取当前登录用户
     *
     * @param request 用户登录态
     * @return 登录用户信息(脱敏)
     */
    @ApiOperation(value = "获取当前登录用户")
    @GetMapping("/get/login")
    @ApiOperationSupport(order = 3)
    public Result<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        LoginUserVO loginUserVO = userService.getLoginUserVO(loginUser);
        return Result.success(loginUserVO);
    }

    /**
     * 用户注销
     *
     * @param request 用户登录态
     * @return 是否注销成功
     */
    @ApiOperation(value = "用户注销")
    @PostMapping("/logout")
    @ApiOperationSupport(order = 4)
    public Result<Boolean> userLogout(HttpServletRequest request) {
        boolean succeed = userService.userLogout(request);
        return Result.success(succeed);
    }

    /**
     * 创建用户(admin)
     *
     * @param addRequest 创建参数
     * @return 新增用户 id
     */
    @ApiOperation(value = "创建用户 (管理员)")
    @PostMapping("/add")
    @ApiOperationSupport(order = 6)
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Long> addUser(@RequestBody com.zp.domain.request.user.UserAddRequest addRequest) {
        ThrowUtils.throwIf(addRequest == null, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtil.copyProperties(addRequest, user);
        // 默认密码
        final String password = "12345678";
        String encryptPassword = userService.encryptPassword(password);
        user.setUserPassword(encryptPassword);
        boolean saved = userService.save(user);
        ThrowUtils.throwIf(!saved, ErrorCode.OPERATION_ERROR, "保存用户失败");
        return Result.success(user.getId());
    }


    /**
     * 删除用户(admin)
     *
     * @param deleteRequest id
     * @return 是否删除成功
     */
    @ApiOperation(value = "删除用户 (管理员)")
    @PostMapping("/delete")
    @ApiOperationSupport(order = 7)
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        boolean removed = userService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!removed, ErrorCode.OPERATION_ERROR, "删除用户失败");
        return Result.success(true);
    }

    /**
     * 更新用户(admin)
     *
     * @param updateRequest 更新参数
     * @return 是否更新成功
     */
    @ApiOperation(value = "更新用户 (管理员)")
    @PostMapping("/update")
    @ApiOperationSupport(order = 8)
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Boolean> updateUser(@RequestBody com.zp.domain.request.user.UserUpdateRequest updateRequest) {
        ThrowUtils.throwIf(updateRequest == null || updateRequest.getId() <= 0, ErrorCode.PARAMS_ERROR);
        User user = new User();
        BeanUtil.copyProperties(updateRequest, user);
        boolean updated = userService.updateById(user);
        ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "更新用户失败");
        return Result.success(true);
    }


    /**
     * 根据 id 获取用户(admin, 未脱敏)
     *
     * @param id 用户 id
     * @return 用户信息
     */
    @ApiOperation(value = "根据 id 获取用户 (管理员)")
    @GetMapping("/get")
    @ApiOperationSupport(order = 9)
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<User> getUserById(@RequestParam("id") Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(user), ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        return Result.success(user);
    }

    /**
     * 根据 id 获取用户信息(脱敏)
     *
     * @param id 用户 id
     * @return 用户信息(脱敏)
     */
    @ApiOperation(value = "根据 id 获取用户信息")
    @GetMapping("/get/vo")
    @ApiOperationSupport(order = 5)
    public Result<UserVO> getUserVOById(@RequestParam("id") Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getById(id);
        ThrowUtils.throwIf(ObjUtil.isNull(user), ErrorCode.NOT_FOUND_ERROR, "用户不存在");
        UserVO userVO = userService.getUserVO(user);
        return Result.success(userVO);
    }

    /**
     * 获取用户列表(admin)
     *
     * @param userQueryRequest 查询参数
     * @return 用户列表
     */
    @ApiOperation(value = "分页获取用户列表 (管理员)")
    @PostMapping("/list/page/vo")
    @ApiOperationSupport(order = 10)
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public Result<Page<UserVO>> listUserVOByPage(@RequestBody com.zp.domain.request.user.UserQueryRequest userQueryRequest) {
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR);
        int current = userQueryRequest.getCurrent();
        int pageSize = userQueryRequest.getPageSize();
        Page<User> page = new Page<>(current, pageSize);
        QueryWrapper<User> queryWrapper = userService.getQueryWrapper(userQueryRequest);
        Page<User> userPage = userService.page(page, queryWrapper);
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        List<UserVO> userVOPageList = userService.getUserVOList(userPage.getRecords());
        userVOPage.setRecords(userVOPageList);
        return Result.success(userVOPage);
    }

    /**
     * 获取图形验证码
     */
    @GetMapping("/captcha")
    public Result<CaptchaVO> captcha() {
        return Result.success(userService.getCaptcha());
    }

    /**
     * 根据 id 获取用户详情
     *
     * @param userId  用户 id
     * @param request 当前登录用户
     * @return 用户详情
     */
    @GetMapping("/detail")
    public Result<UserDetailVO> getUserDetailById(Long userId, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(ObjUtil.isNull(loginUser), ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(ObjUtil.isEmpty(userId), ErrorCode.PARAMS_ERROR);
        User user = userService.getById(userId);
        UserDetailVO userDetailVO = new UserDetailVO();
        BeanUtil.copyProperties(user, userDetailVO);
        return Result.success(userDetailVO);
    }


    /**
     * 用户修改个人信息
     *
     * @param editRequest 修改参数
     * @param request     当前登录用户
     * @return 是否修改成功
     */
    @PostMapping("/edit")
    public Result<Boolean> editUser(@RequestBody com.zp.domain.request.user.UserEditRequest editRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(editRequest == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(ObjUtil.isEmpty(editRequest.getUserId()), ErrorCode.PARAMS_ERROR);
        String userPhone = editRequest.getUserPhone();
        if (StrUtil.isNotBlank(userPhone) && userPhone.length() > 11) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号不合法");
        }
        String userProfile = editRequest.getUserProfile();
        if (StrUtil.isNotBlank(userProfile) && userProfile.length() > 512) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "个人简介过长");
        }
        User user = new User();
        BeanUtil.copyProperties(editRequest, user);
        // 关键修复：请求里是 userId 字段，实体更新使用 id 字段
        user.setId(editRequest.getUserId());
        boolean updated = userService.updateById(user);
        ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "修改用户信息失败");
        return Result.success(true);
    }

    /**
     * 用户修改密码
     *
     * @param passwordRequest 修改密码
     * @param request         当前登录用户
     * @return 是否修改成功
     */
    @PostMapping("/password")
    public Result<Boolean> editUserPassword(@RequestBody com.zp.domain.request.user.UserEditPasswordRequest passwordRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(passwordRequest == null, ErrorCode.PARAMS_ERROR);
        String originPassword = passwordRequest.getOriginPassword();
        String newPassword = passwordRequest.getNewPassword();
        String confirmPassword = passwordRequest.getConfirmPassword();
        if (StrUtil.hasBlank(originPassword, newPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码不能为空");
        }
        ThrowUtils.throwIf(!newPassword.equals(confirmPassword), ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        User user = new User();
        BeanUtil.copyProperties(passwordRequest, user);
        User loginUser = userService.getLoginUser(request);
        if (!loginUser.getUserPassword().equals(userService.encryptPassword(originPassword))) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "原密码错误");
        }
        user.setId(loginUser.getId());
        user.setUserPassword(userService.encryptPassword(newPassword));
        boolean updated = userService.updateById(user);
        ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "修改用户密码失败");
        return Result.success(true);
    }

    /**
     * 上传头像
     *
     * @param file    文件
     * @param request 当前登录用户
     * @return 上传后的文件路径
     */
    @PostMapping("/uploadAvatar")
    public Result<String> uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        ThrowUtils.throwIf(file == null, ErrorCode.PARAMS_ERROR);
        String originalFilename = file.getOriginalFilename();
        String suffix = FileUtil.getSuffix(originalFilename);
        Long loginUserId = userService.getLoginUser(request).getId();
        String objectKey = String.format("user/avatar/%d/%s.%s", loginUserId, RandomUtil.randomNumbers(10), suffix);
        String bucket = aliyunOssClient.getBucket();
        try {
            com.aliyun.oss.model.ObjectMetadata metadata = new com.aliyun.oss.model.ObjectMetadata();
            if (StrUtil.equalsIgnoreCase(suffix, "png")) {
                metadata.setContentType("image/png");
            } else if (StrUtil.equalsIgnoreCase(suffix, "jpg") || StrUtil.equalsIgnoreCase(suffix, "jpeg")) {
                metadata.setContentType("image/jpeg");
            } else if (StrUtil.equalsIgnoreCase(suffix, "gif")) {
                metadata.setContentType("image/gif");
            }
            java.io.InputStream inputStream = file.getInputStream();
            ossClient.putObject(bucket, objectKey, inputStream, metadata);
            // 头像需可公开访问
            ossClient.setObjectAcl(bucket, objectKey, com.aliyun.oss.model.CannedAccessControlList.PublicRead);
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }
        String host = aliyunOssClient.getHost();
        if (StrUtil.isBlank(host)) {
            host = String.format("https://%s.%s", bucket, aliyunOssClient.getEndpoint());
        }
        String avatarUrl = host.endsWith("/") ? host + objectKey : host + "/" + objectKey;
        User user = new User();
        user.setId(loginUserId);
        user.setUserAvatar(avatarUrl);
        boolean updated = userService.updateById(user);
        ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "修改用户头像失败");
        // 刷新会话中的用户信息，前端重新拉取 /user/get/login 可立即显示
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, userService.getById(loginUserId));
        return Result.success(avatarUrl);
    }
}